﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.LeisportariasPack
{
    [Serializable()]
    public class Leisportarias : BusinessBase<Leisportarias>
    {
        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private String _titulo = String.Empty;

        private String _descricao = String.Empty;

        private String _arquivo = String.Empty;

        private DateTime _dataPublicacao = DateTime.Now;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public String Titulo
        {
            get
            {
                CanReadProperty("Titulo", true);
                return _titulo;
            }
            set
            {
                CanWriteProperty("Titulo", true);
                if (value == null) value = String.Empty;
                if (!_titulo.Equals(value))
                {
                    _titulo = value;
                    PropertyHasChanged("Titulo");
                }
            }
        }

        public String Descricao
        {
            get
            {
                CanReadProperty("Descricao", true);
                return _descricao;
            }
            set
            {
                CanWriteProperty("Descricao", true);
                if (value == null) value = String.Empty;
                if (!_descricao.Equals(value))
                {
                    _descricao = value;
                    PropertyHasChanged("Descricao");
                }
            }
        }

        public String Arquivo
        {
            get
            {
                CanReadProperty("Arquivo", true);
                return _arquivo;
            }
            set
            {
                CanWriteProperty("Arquivo", true);
                if (value == null) value = String.Empty;
                if (!_arquivo.Equals(value))
                {
                    _arquivo = value;
                    PropertyHasChanged("Arquivo");
                }
            }
        }

        public String ArquivoString
        {
            get
            {
                CanReadProperty("ArquivoString", true);
                if (_arquivo.Contains("_"))
                    return _arquivo.Substring(_arquivo.IndexOf("_") + 1);
                return _arquivo;
            }
        }

        public DateTime DataPublicacao
        {
            get
            {
                CanReadProperty("DataPublicacao", true);
                return _dataPublicacao;
            }
            set
            {
                CanWriteProperty("DataPublicacao", true);
                if (!_dataPublicacao.Equals(value))
                {
                    _dataPublicacao = value;
                    PropertyHasChanged("DataPublicacao");
                }
            }
        }

        public String DataShortString
        {
            get
            {
                CanReadProperty("DataPublicacao", true);
                return _dataPublicacao.ToString("dd/MM/yyyy");
            }
        }

        public String DataFullString
        {
            get
            {
                CanReadProperty("DataPublicacao", true);
                return _dataPublicacao.ToString("dd/MM/yyyy HH:mm");
            }
        }


        protected override object GetIdValue()
        {
            return _id.ToString();
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
        }


        public static bool CanGetObject()
        {
            return true;
        }

        public static bool CanAddObject()
        {
            return true;
        }

        public static bool CanEditObject()
        {
            return true;
        }

        public static bool CanDeleteObject()
        {
            return true;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Leisportarias()
        { /* require use of factory method */ }

        public static Leisportarias NewLeisportarias()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Leisportarias");
            return DataPortal.Create<Leisportarias>();
        }

        public static Leisportarias GetLeisportarias(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Leisportarias");
            return DataPortal.Fetch<Leisportarias>(new Criteria(id));
        }

        public override Leisportarias Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Leisportarias");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Leisportarias");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Leisportarias");

            return base.Save();
        }

        public static void DeleteLeisportarias(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Leisportarias");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;

            }
        }


        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteFetch(cn, criteria);
            }//using

        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();



                    //load child object(s)
                    FetchChildren(dr);
                }
            }//using
        }

        private String GetFetchScript(Criteria criteria)
        {
            return "SELECT Id, Titulo, Descricao, Arquivo, DataPublicacao "
                 + "FROM leisportariastb WHERE Id=\"" + criteria.Id.ToString().Replace("\"", "\\\"") + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;

            _id = new Guid(dr["Id"].ToString());
            _titulo = dr.GetString("Titulo");
            _descricao = dr.GetString("Descricao");
            _arquivo = dr.GetString("Arquivo");
            _dataPublicacao = dr.GetDateTime("DataPublicacao");

        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteInsert(cn);

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - leisportariastb - Id: " + _id.ToString());
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();

                cm.ExecuteNonQuery();



            }//using
        }

        private String GetInsertScript()
        {
            return "INSERT INTO leisportariastb(Id, Titulo, Descricao, Arquivo, DataPublicacao) VALUES (\""
                + _id.ToString().Replace("\"", "\\\"") + "\", \""
                + _titulo.ToString().Replace("\"", "\\\"") + "\", \""
                + _descricao.ToString().Replace("\"", "\\\"") + "\", \""
                + _arquivo.ToString().Replace("\"", "\\\"") + "\", \""
                + _dataPublicacao.ToString("yyyy-MM-dd HH:mm:ss") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - leisportariastb - Id: " + _id.ToString());
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private String GetUpdateScript()
        {
            return "Update leisportariastb set "
                    + "Titulo=\"" + _titulo.ToString().Replace("\"", "\\\"") + "\", "
                    + "Descricao=\"" + _descricao.ToString().Replace("\"", "\\\"") + "\", "
                    + "Arquivo=\"" + _arquivo.ToString().Replace("\"", "\\\"") + "\" "
                    + " WHERE Id=\"" + _id.ToString().Replace("\"", "\\\"") + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - leisportariastb - Id: " + _id.ToString());
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from leisportariastb WHERE Id=\"" + criteria.Id.ToString().Replace("\"", "\\\"") + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
